rm(list = ls())

options(scipen=999)
set.seed(02138)

library(mediation)
library(tidyverse)

## Get data

dat <- readRDS('data/elec_mediation_df.rds') %>%
  mutate(mediator1_binary = ifelse(mediator1 > median(mediator1), 1, 0))

## Mediator models 

med_fit_1 <- lm(mediator1 ~ treat_either, data = dat)
med_fit_2 <- lm(mediator1 ~ treat_either + land, data = dat)
med_fit_3 <- lm(mediator1_binary ~ treat_either, data = dat)
med_fit_4 <- lm(mediator1_binary ~ treat_either + land, data = dat)

## Outcome models 

out_fit_1 <- lm(diff_greens ~ treat_either + mediator1, data = dat)
out_fit_2 <- lm(diff_greens ~ treat_either + mediator1 + land, data = dat)
out_fit_3 <- lm(diff_greens ~ treat_either + mediator1_binary, data = dat)
out_fit_4 <- lm(diff_greens ~ treat_either + mediator1_binary + land, data = dat)

## Mediation Analysis 

med_out_1 <- mediate(model.m = med_fit_1, 
                     model.y = out_fit_1, 
                     treat = 'treat_either', 
                     mediator = 'mediator1',
                     sims = 1000, 
                     cluster = dat$county_id)

med_out_2 <- mediate(model.m = med_fit_2, 
                     model.y = out_fit_2, 
                     treat = 'treat_either', 
                     mediator = 'mediator1',
                     sims = 1000, 
                     cluster = dat$county_id)

med_out_3 <- mediate(model.m = med_fit_3, 
                     model.y = out_fit_3, 
                     treat = 'treat_either', 
                     mediator = 'mediator1_binary',
                     sims = 1000, 
                     cluster = dat$county_id)

med_out_4 <- mediate(model.m = med_fit_4, 
                     model.y = out_fit_4, 
                     treat = 'treat_either', 
                     mediator = 'mediator1_binary',
                     sims = 1000, 
                     cluster = dat$county_id)

## Results 

summary(med_out_1)
summary(med_out_2)
summary(med_out_3)
summary(med_out_4)




